<template>
  <div id="detail">
    <detail-nav-bar class="detail-nav" @titleClick="titleClick" ref="nav" />
    <scroll class="content" ref="scroll" @scroll="contentScroll" :probe-type="3" >
      <detail-swiper :top-images="topImages" />
      <!-- 把数据保存到实例上，然后在把这个实例传给子组件，子组件使用props接收数据 -->
      <detail-base-info :goods="goods" />
      <detail-shop-info :shop="shop" />
      <detail-goods-info :detail-info="detailInfo" @imageLoad="imageLoad" />
      <detail-param-info :param-info="paramInfo" ref="param" />
      <detail-comment-info :commentInfo="commentInfo" ref="comment" />
      <goods-list :goods="recommends" ref="recommend" />
    </scroll>
    <detail-bottom-bar @addToCart="addToCart" />
    <back-top @click.native="backTop" v-show="isShowBackTop" />
    </div>
</template>

<script>
import DetailNavBar from './childComps/DetailNavBar'
import DetailSwiper from './childComps/DetailSwiper'
import DetailBaseInfo from './childComps/DetailBaseInfo'
import DetailShopInfo from './childComps/DetailShopInfo'
import DetailGoodsInfo from './childComps/DetailGoodsInfo'
import DetailParamInfo from './childComps/DetailParamInfo'
import DetailCommentInfo from './childComps/DetailCommentInfo'
import DetailBottomBar from './childComps/DetailBottomBar'

import Scroll from 'components/common/scroll/Scroll.vue'
import GoodsList from 'components/content/goods/GoodsList.vue'

import { getDetail, getRecommend, Goods, Shop, GoodsParam } from 'network/detail.js'

import { debounce } from 'common/utils.js'

import { itemListenerMixin, backTopMixin } from 'common/mixin.js'

import { mapActions } from 'vuex'

export default {
  name: 'Detail',
  data() {
    return {
      iid: null,
      topImages: [],
      goods: {},
      shop: {},
      detailInfo: {},
      paramInfo: {},
      commentInfo: {},
      recommends: [],
      themeTopYs: [0, 1000, 2000, 3000],
      getThemeTopY: null,
      currentIndex: 0,
    }
  },
  mixins: [itemListenerMixin, backTopMixin],
  components: {
    DetailNavBar,
    DetailSwiper,
    DetailBaseInfo,
    DetailShopInfo,
    Scroll,
    DetailGoodsInfo,
    DetailParamInfo,
    DetailCommentInfo,
    GoodsList,
    DetailBottomBar,
  },
  created() {
    this.iid = this.$route.params.iid
    // 获取商品详情
    getDetail(this.iid).then(res => {
      // console.log(res);
      const data = res.result
      // 获取轮播图片数据
      this.topImages = data.itemInfo.topImages
      // 获取商品信息，Goods是一个构造函数，可以通过new来创建实例
      this.goods = new Goods(data.itemInfo, data.columns, data.shopInfo.services)
      // 获取店铺信息
      this.shop = new Shop(data.shopInfo)
      // 获取商品详细信息
      this.detailInfo = data.detailInfo
      // 获取店铺商品信息
      this.paramInfo = new GoodsParam(data.itemParams.info, data.itemParams.rule)
      // 获取评论信息
      if(data.rate.cRate) {
        this.commentInfo = data.rate.list[0]
      }
    })

    // 获取推荐信息
    getRecommend().then(res => {
      this.recommends = res.data.list
    })

    // 先给getThemeTopY赋值，每次等图片加载的时候，去调用这个函数
    this.getThemeTopY = debounce(() => {
      // 先把上一次的清空掉
      this.themeTopYs = []
      this.themeTopYs.push(0)
      // 注意：这里不能直接使用offsetTop，前面需要加上$el.offsetTop
      this.themeTopYs.push(this.$refs.param.$el.offsetTop)
      this.themeTopYs.push(this.$refs.comment.$el.offsetTop)
      this.themeTopYs.push(this.$refs.recommend.$el.offsetTop)
      this.themeTopYs.push(Number.MAX_VALUE)
    }, 100)
  },
  methods: {
    imageLoad() {
      // console.log('detail中调用');
      this.$refs.scroll.refresh()
      // 当图片加载完成的时候，我们再去获取相应组件的offsetTop值，这里的函数是经过防抖处理的
      this.getThemeTopY()
    },
    titleClick(index) {
      // 从子组件navbar中传过来的index
      // console.log(index);
      // 点击导航条，跳转到相应的位置，跳转的时间是200ms
      this.$refs.scroll.scrollTo(0, -this.themeTopYs[index], 200)
    },
    contentScroll(position) {
      // 在使用回到顶部按钮的时候，可以直接使用下面这行代码，当然也可以再次封装成一个函数
      // this.isShowBackTop = Math.abs(position.y) > 1000
      //1.判断BackTop是否显示
      this.listenShowBackTop(position);

      // 真正用到的是position中的y值，并且需要取反
      const positionY = -position.y
      let length = this.themeTopYs.length

      // themeTopYs: [0, 1000, 2000, 3000]  3
      for(let i = 0; i < length - 1; i++) {
        if(this.currentIndex !== i && (positionY >= this.themeTopYs[i] && positionY < this.themeTopYs[i + 1])) {
          // console.log(i);
          this.currentIndex = i
          this.$refs.nav.currentIndex = this.currentIndex
        }
      }
    },
    ...mapActions(['addCart']),
    // 添加到购物车事件的函数
    addToCart() {
      // 获取所需要的信息
      const product = {}
      product.image = this.topImages[0]
      product.title = this.goods.title
      product.desc = this.goods.desc
      product.price = this.goods.realPrice
      product.iid = this.iid

      // console.log(product);
      // 这是直接通过mutations去修改数据
      // this.$store.commit('addCart', product)
      // 先通过actions去dispatch，再通过mutations去commit，修改数据
      // 因为返回的是一个Promise，所以需要用then来接收参数
      // this.$store.dispatch('addCart', product).then(res => {
      //   console.log(res);
      // })
      // 和mapGetters一样，这里可以使用mapActions改变映射关系
      this.addCart(product).then(res => {
        // this.message = res
        // this.isShow = true
        // // console.log(res);
        // setTimeout(() => {
        //   this.isShow = false
        // }, 1500);

        // 直接调用$toast方法
        this.$toast.show(res, 1500)
      })
    }
  },
}
</script>

<style scoped>
  #detail {
    position: relative;
    height: 100vh;
    background-color: #fff;
    z-index: 9;
  }
  .content {
    /* height: calc(100% - 44px); */
    /* 也可以用绝对定位 */
    position: absolute;
    top: 44px;
    bottom: 60px;
    width: 100%;
  }
  .detail-nav {
    position: relative;
    background-color: #fff;
    z-index: 9;
  }
</style>